package com.yingside.gui.book;

import com.lovo.netCRM.component.LovoButton;
import com.lovo.netCRM.component.LovoTxt;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class BookEditFrame extends JFrame {

    private LovoTxt txtId,txtBookName,txtAuthor,txtPrice;
    private LovoButton btnEdit,btnCancel;
    private IBookManager bookManager = new BookManagerImpl();
    private BookMainFrame bookMainFrame;

    public BookEditFrame(BookMainFrame bookMainFrame, int key){
        this.bookMainFrame = bookMainFrame;
        this.setTitle("LovoTable修改窗口");
        this.setBounds(300, 300, 400, 400);
        this.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
        this.setLayout(null);
        initComponent(key);
    }

    public void initComponent(int key){

        Book book = bookManager.get(key);

        txtId = new LovoTxt("编号",30,30,this);
        txtBookName = new LovoTxt("名称",30,80,this);
        txtAuthor = new LovoTxt("作者",30,130,this);
        txtPrice = new LovoTxt("价格",30,180,this);

        txtId.setText(String.valueOf(book.getId()));
        txtBookName.setText(book.getBookName());
        txtAuthor.setText(book.getAuthor());
        txtPrice.setText(String.valueOf(book.getPrice()));

        btnEdit = new LovoButton("修改",50,220,this);
        btnCancel = new LovoButton("取消",160,220,this);

        btnEdit.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                int id = Integer.parseInt(txtId.getText());
                String bookName = txtBookName.getText();
                String author = txtAuthor.getText();
                double price = Double.parseDouble(txtPrice.getText());

                Book b = new Book(id,bookName,author,price);

                boolean flag = bookManager.update(b);

                if(flag){
                    JOptionPane.showMessageDialog(null,"新增成功");
                    bookMainFrame.initData();
                }
                else{
                    JOptionPane.showMessageDialog(null,"新增失败");
                }
            }
        });

        btnCancel.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                //关闭当前新增窗口
                BookEditFrame.this.dispose();
                bookMainFrame.getBtnAdd().setEnabled(true);
            }
        });
    }
}
